<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="谷歌的教程没有中文而且感觉太难了点，还是试试这个教程吧orz">
<meta property="og:type" content="article">
<meta property="og:title" content="通过例子学 Rust">
<meta property="og:url" content="https://wyatex.online/Rust/rust-by-example-1/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="谷歌的教程没有中文而且感觉太难了点，还是试试这个教程吧orz">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-03-25T08:04:58.000Z">
<meta property="article:modified_time" content="2023-05-05T01:25:47.239Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="Rust">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://wyatex.online/Rust/rust-by-example-1/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/Rust/rust-by-example-1/","path":"Rust/rust-by-example-1/","title":"通过例子学 Rust"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>通过例子学 Rust | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#HelloWorld"><span class="nav-number">1.</span> <span class="nav-text">HelloWorld</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%A8%E9%87%8A"><span class="nav-number">1.1.</span> <span class="nav-text">注释</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A0%BC%E5%BC%8F%E5%8C%96%E8%BE%93%E5%87%BA"><span class="nav-number">1.2.</span> <span class="nav-text">格式化输出</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B0%83%E8%AF%95%EF%BC%88Debug%EF%BC%89"><span class="nav-number">1.3.</span> <span class="nav-text">调试（Debug）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A0%BC%E5%BC%8F%E5%8C%96"><span class="nav-number">1.4.</span> <span class="nav-text">格式化</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E7%94%9F%E7%B1%BB%E5%9E%8B"><span class="nav-number">2.</span> <span class="nav-text">原生类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%A0%87%E9%87%8F%E7%B1%BB%E5%9E%8B%EF%BC%88scalar-type%EF%BC%89"><span class="nav-number">2.1.</span> <span class="nav-text">标量类型（scalar type）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%8D%E5%90%88%E7%B1%BB%E5%9E%8B%EF%BC%88compound-type%EF%BC%89"><span class="nav-number">2.2.</span> <span class="nav-text">复合类型（compound type）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E9%9D%A2%E9%87%8F%E5%92%8C%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="nav-number">2.3.</span> <span class="nav-text">字面量和运算符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%83%E7%BB%84"><span class="nav-number">2.4.</span> <span class="nav-text">元组</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E5%92%8C%E5%88%87%E7%89%87"><span class="nav-number">2.5.</span> <span class="nav-text">数组和切片</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%B1%BB%E5%9E%8B"><span class="nav-number">3.</span> <span class="nav-text">自定义类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%BB%93%E6%9E%84%E4%BD%93"><span class="nav-number">3.1.</span> <span class="nav-text">结构体</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9E%9A%E4%B8%BE"><span class="nav-number">3.2.</span> <span class="nav-text">枚举</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%B1%BB%E5%9E%8B%E5%88%AB%E5%90%8D"><span class="nav-number">3.2.1.</span> <span class="nav-text">类型别名</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/Rust/rust-note-course-1/" rel="bookmark">
        <time class="popular-posts-time">2024-01-03</time>
        <br>
      Rust圣经学习笔记（1）
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/Rust/rust-by-example-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="通过例子学 Rust | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          通过例子学 Rust
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-03-25 16:04:58" itemprop="dateCreated datePublished" datetime="2023-03-25T16:04:58+08:00">2023-03-25</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2023-05-05 09:25:47" itemprop="dateModified" datetime="2023-05-05T09:25:47+08:00">2023-05-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Rust/" itemprop="url" rel="index"><span itemprop="name">Rust</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>谷歌的教程没有中文而且感觉太难了点，还是试试这个教程吧orz</p>
<span id="more"></span>

<h2 id="HelloWorld"><a href="#HelloWorld" class="headerlink" title="HelloWorld"></a>HelloWorld</h2><figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这是注释内容，将会被编译器忽略掉</span></span><br><span class="line"><span class="comment">// 可以单击那边的按钮 &quot;Run&quot; 来测试这段代码 -&gt;</span></span><br><span class="line"><span class="comment">// 若想用键盘操作，可以使用快捷键 &quot;Ctrl + Enter&quot; 来运行</span></span><br><span class="line"><span class="comment">// 这段代码支持编辑，你可以自由地修改代码！</span></span><br><span class="line"><span class="comment">// 通过单击 &quot;Reset&quot; 按钮可以使代码恢复到初始状态 -&gt;</span></span><br><span class="line"><span class="comment">// 这是主函数</span></span><br><span class="line"><span class="keyword">fn</span> <span class="title function_">main</span>() &#123;</span><br><span class="line">    <span class="comment">// 调用编译生成的可执行文件时，这里的语句将被运行。</span></span><br><span class="line">    <span class="comment">// 将文本打印到控制台</span></span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;Hello World!&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>println!</code> 是一个[<strong>宏</strong>][macros]（macros），可以将文本输出到控制台（console）。</p>
<p>使用 Rust 的编译器 <code>rustc</code> 可以从源程序生成可执行文件：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">rustc hello.rs</span><br></pre></td></tr></table></figure>

<p>使用 <code>rustc</code> 编译后将得到可执行文件 <code>hello</code>。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$ ./hello</span><br><span class="line">Hello World!</span><br></pre></td></tr></table></figure>

<h3 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h3><p>注释对任何程序都不可缺少，同样 Rust 支持几种不同的注释方式。</p>
<ul>
<li><strong>普通注释</strong>，其内容将被编译器忽略掉：<ul>
<li><code>// 单行注释，注释内容直到行尾。</code></li>
<li><code>/* 块注释，注释内容一直到结束分隔符。 */</code></li>
</ul>
</li>
<li><strong>文档注释</strong>，其内容将被解析成 HTML 帮助[文档][docs]：<ul>
<li><code>/// 为接下来的项生成帮助文档。</code></li>
<li><code>//! 为注释所属于的项（译注：如 crate、模块或函数）生成帮助文档。</code></li>
</ul>
</li>
</ul>
<h3 id="格式化输出"><a href="#格式化输出" class="headerlink" title="格式化输出"></a>格式化输出</h3><p>打印操作由 [<code>std::fmt</code>][fmt] 里面所定义的一系列[宏][macros]来处理，包括：</p>
<ul>
<li><code>format!</code>：将格式化文本写到[字符串][string]。</li>
<li><code>print!</code>：与 <code>format!</code> 类似，但将文本输出到控制台（io::stdout）。</li>
<li><code>println!</code>: 与 <code>print!</code> 类似，但输出结果追加一个换行符。</li>
<li><code>eprint!</code>：与 <code>print!</code> 类似，但将文本输出到标准错误（io::stderr）。</li>
<li><code>eprintln!</code>：与 <code>eprint!</code> 类似，但输出结果追加一个换行符。</li>
</ul>
<p>这些宏都以相同的做法解析文本。有个额外优点是格式化的正确性会在编译时检查。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">fn main() &#123;</span><br><span class="line">    // 通常情况下，`&#123;&#125;` 会被任意变量内容所替换。</span><br><span class="line">    // 变量内容会转化成字符串。</span><br><span class="line">    println!(&quot;&#123;&#125; days&quot;, 31);</span><br><span class="line">    // 不加后缀的话，31 就自动成为 i32 类型。</span><br><span class="line">    // 你可以添加后缀来改变 31 的类型（例如使用 31i64 声明 31 为 i64 类型）。</span><br><span class="line">    // 用变量替换字符串有多种写法。</span><br><span class="line">    // 比如可以使用位置参数。</span><br><span class="line">    println!(&quot;&#123;0&#125;, this is &#123;1&#125;. &#123;1&#125;, this is &#123;0&#125;&quot;, &quot;Alice&quot;, &quot;Bob&quot;);</span><br><span class="line">    // 可以使用命名参数。</span><br><span class="line">    println!(&quot;&#123;subject&#125; &#123;verb&#125; &#123;object&#125;&quot;,</span><br><span class="line">             object=&quot;the lazy dog&quot;,</span><br><span class="line">             subject=&quot;the quick brown fox&quot;,</span><br><span class="line">             verb=&quot;jumps over&quot;);</span><br><span class="line">    // 可以在 `:` 后面指定特殊的格式。</span><br><span class="line">    println!(&quot;&#123;&#125; of &#123;:b&#125; people know binary, the other half don&#x27;t&quot;, 1, 2);</span><br><span class="line">    // 你可以按指定宽度来右对齐文本。</span><br><span class="line">    // 下面语句输出 &quot;     1&quot;，5 个空格后面连着 1。</span><br><span class="line">    println!(&quot;&#123;number:&gt;width$&#125;&quot;, number=1, width=6);</span><br><span class="line">    // 你可以在数字左边补 0。下面语句输出 &quot;000001&quot;。</span><br><span class="line">    println!(&quot;&#123;number:&gt;0width$&#125;&quot;, number=1, width=6);</span><br><span class="line">    // println! 会检查使用到的参数数量是否正确。</span><br><span class="line">    println!(&quot;My name is &#123;0&#125;, &#123;1&#125; &#123;0&#125;&quot;, &quot;Bond&quot;);</span><br><span class="line">    // 改正 ^ 补上漏掉的参数：&quot;James&quot;</span><br><span class="line">    // 创建一个包含单个 `i32` 的结构体（structure）。命名为 `Structure`。</span><br><span class="line">    #[allow(dead_code)]</span><br><span class="line">    struct Structure(i32);</span><br><span class="line">    // 但是像结构体这样的自定义类型需要更复杂的方式来处理。</span><br><span class="line">    // 下面语句无法运行。</span><br><span class="line">    println!(&quot;This struct `&#123;&#125;` won&#x27;t print...&quot;, Structure(3));</span><br><span class="line">    // 改正 ^ 注释掉此行。</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>[<code>std::fmt</code>][fmt] 包含多种 [<code>trait</code>][traits]（特质）来控制文字显示，其中重要的两种 trait 的基本形式如下：</p>
<ul>
<li><code>fmt::Debug</code>：使用 <code>&#123;:?&#125;</code> 标记。格式化文本以供调试使用。</li>
<li><code>fmt::Display</code>：使用 <code>&#123;&#125;</code> 标记。以更优雅和友好的风格来格式化文本。</li>
</ul>
<p>上例使用了 <code>fmt::Display</code>，因为标准库提供了那些类型的实现。若要打印自定义类型的文本，需要更多的步骤。</p>
<h3 id="调试（Debug）"><a href="#调试（Debug）" class="headerlink" title="调试（Debug）"></a>调试（Debug）</h3><p>所有的类型，若想用 <code>std::fmt</code> 的格式化打印，都要求实现至少一个可打印的 <code>traits</code>。仅有一些类型提供了自动实现，比如 <code>std</code> 库中的类型。所有其他类型都<strong>必须</strong>手动实现。</p>
<p><code>fmt::Debug</code> 这个 <code>trait</code> 使这项工作变得相当简单。所有类型都能推导（<code>derive</code>，<strong>即自动创建</strong>）<code>fmt::Debug</code> 的实现。但是 <code>fmt::Display</code> 需要手动实现。</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这个结构体不能使用 `fmt::Display` 或 `fmt::Debug` 来进行打印。</span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">UnPrintable</span>(<span class="type">i32</span>);</span><br><span class="line"><span class="comment">// `derive` 属性会自动创建所需的实现，使这个 `struct` 能使用 `fmt::Debug` 打印。</span></span><br><span class="line"><span class="meta">#[derive(Debug)]</span></span><br><span class="line"><span class="keyword">struct</span> <span class="title class_">DebugPrintable</span>(<span class="type">i32</span>);</span><br></pre></td></tr></table></figure>

<p>所有 <code>std</code> 库类型都天生可以使用 <code>&#123;:?&#125;</code> 来打印：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">// 推导 `Structure` 的 `fmt::Debug` 实现。</span><br><span class="line">// `Structure` 是一个包含单个 `i32` 的结构体。</span><br><span class="line">#[derive(Debug)]</span><br><span class="line">struct Structure(i32);</span><br><span class="line">// 将 `Structure` 放到结构体 `Deep` 中。然后使 `Deep` 也能够打印。</span><br><span class="line">#[derive(Debug)]</span><br><span class="line">struct Deep(Structure);</span><br><span class="line">fn main() &#123;</span><br><span class="line">    // 使用 `&#123;:?&#125;` 打印和使用 `&#123;&#125;` 类似，就是使用fmt::Debug来打印。</span><br><span class="line">    println!(&quot;&#123;:?&#125; months in a year.&quot;, 12);</span><br><span class="line">    println!(&quot;&#123;1:?&#125; &#123;0:?&#125; is the &#123;actor:?&#125; name.&quot;,</span><br><span class="line">             &quot;Slater&quot;,</span><br><span class="line">             &quot;Christian&quot;,</span><br><span class="line">             actor=&quot;actor&#x27;s&quot;);</span><br><span class="line">    // `Structure` 也可以打印！</span><br><span class="line">    println!(&quot;Now &#123;:?&#125; will print!&quot;, Structure(3));</span><br><span class="line">    </span><br><span class="line">    // 使用 `derive` 的一个问题是不能控制输出的形式。</span><br><span class="line">    // 假如我只想展示一个 `7` 怎么办？</span><br><span class="line">    println!(&quot;Now &#123;:?&#125; will print!&quot;, Deep(Structure(7)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>所以 <code>fmt::Debug</code> 确实使这些内容可以打印，但是牺牲了一些美感。Rust 也通过 <code>&#123;:#?&#125;</code> 提供了 “美化打印” 的功能：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">#[derive(Debug)]</span><br><span class="line">struct Person&lt;&#x27;a&gt; &#123;</span><br><span class="line">    name: &amp;&#x27;a str,</span><br><span class="line">    age: u8</span><br><span class="line">&#125;</span><br><span class="line">fn main() &#123;</span><br><span class="line">    let name = &quot;Peter&quot;;</span><br><span class="line">    let age = 27;</span><br><span class="line">    let peter = Person &#123; name, age &#125;;</span><br><span class="line">    // 美化打印</span><br><span class="line">    println!(&quot;&#123;:#?&#125;&quot;, peter);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>你可以通过手动实现 <code>fmt::Display</code> 来控制显示效果。</p>
<h3 id="格式化"><a href="#格式化" class="headerlink" title="格式化"></a>格式化</h3><p>我们已经看到，格式化的方式是通过<strong>格式字符串</strong>来指定的：</p>
<ul>
<li><code>format!(&quot;&#123;&#125;&quot;, foo)</code> -&gt; <code>&quot;3735928559&quot;</code></li>
<li><code>format!(&quot;0x&#123;:X&#125;&quot;, foo)</code> -&gt;<br>[<code>&quot;0xDEADBEEF&quot;</code>][deadbeef]</li>
<li><code>format!(&quot;0o&#123;:o&#125;&quot;, foo)</code> -&gt; <code>&quot;0o33653337357&quot;</code></li>
</ul>
<p>根据使用的<strong>参数类型</strong>是 <code>X</code>、<code>o</code> 还是<strong>未指定</strong>，同样的变量（<code>foo</code>）能够格式化成不同的形式。</p>
<p>这个格式化的功能是通过 trait 实现的，每种参数类型都对应一种 trait。最常见的格式化 trait 就是 <code>Display</code>，它可以处理参数类型为未指定的情况，比如 <code>&#123;&#125;</code>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">use std::fmt::&#123;self, Formatter, Display&#125;;</span><br><span class="line">struct City &#123;</span><br><span class="line">    name: &amp;&#x27;static str,</span><br><span class="line">    // 纬度</span><br><span class="line">    lat: f32,</span><br><span class="line">    // 经度</span><br><span class="line">    lon: f32,</span><br><span class="line">&#125;</span><br><span class="line">impl Display for City &#123;</span><br><span class="line">    // `f` 是一个缓冲区（buffer），此方法必须将格式化后的字符串写入其中</span><br><span class="line">    fn fmt(&amp;self, f: &amp;mut Formatter) -&gt; fmt::Result &#123;</span><br><span class="line">        let lat_c = if self.lat &gt;= 0.0 &#123; &#x27;N&#x27; &#125; else &#123; &#x27;S&#x27; &#125;;</span><br><span class="line">        let lon_c = if self.lon &gt;= 0.0 &#123; &#x27;E&#x27; &#125; else &#123; &#x27;W&#x27; &#125;;</span><br><span class="line">        // `write!` 和 `format!` 类似，但它会将格式化后的字符串写入</span><br><span class="line">        // 一个缓冲区（即第一个参数f）中。</span><br><span class="line">        write!(f, &quot;&#123;&#125;: &#123;:.3&#125;°&#123;&#125; &#123;:.3&#125;°&#123;&#125;&quot;,</span><br><span class="line">               self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">#[derive(Debug)]</span><br><span class="line">struct Color &#123;</span><br><span class="line">    red: u8,</span><br><span class="line">    green: u8,</span><br><span class="line">    blue: u8,</span><br><span class="line">&#125;</span><br><span class="line">fn main() &#123;</span><br><span class="line">    for city in [</span><br><span class="line">        City &#123; name: &quot;Dublin&quot;, lat: 53.347778, lon: -6.259722 &#125;,</span><br><span class="line">        City &#123; name: &quot;Oslo&quot;, lat: 59.95, lon: 10.75 &#125;,</span><br><span class="line">        City &#123; name: &quot;Vancouver&quot;, lat: 49.25, lon: -123.1 &#125;,</span><br><span class="line">    ].iter() &#123;</span><br><span class="line">        println!(&quot;&#123;&#125;&quot;, *city);</span><br><span class="line">    &#125;</span><br><span class="line">    for color in [</span><br><span class="line">        Color &#123; red: 128, green: 255, blue: 90 &#125;,</span><br><span class="line">        Color &#123; red: 0, green: 3, blue: 254 &#125;,</span><br><span class="line">        Color &#123; red: 0, green: 0, blue: 0 &#125;,</span><br><span class="line">    ].iter() &#123;</span><br><span class="line">        // 在添加了针对 fmt::Display 的实现后，请改用 &#123;&#125; 检验效果。</span><br><span class="line">        println!(&quot;&#123;:?&#125;&quot;, *color)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在 [<code>fmt::fmt</code>][fmt] 文档中可以查看[格式化 traits 一览表][fmt_traits]和它们的参数类型。</p>
<h2 id="原生类型"><a href="#原生类型" class="headerlink" title="原生类型"></a>原生类型</h2><p>Rust 提供了多种原生类型（<code>primitives</code>），包括：</p>
<h3 id="标量类型（scalar-type）"><a href="#标量类型（scalar-type）" class="headerlink" title="标量类型（scalar type）"></a>标量类型（scalar type）</h3><ul>
<li>有符号整数（signed integers）：<code>i8</code>、<code>i16</code>、<code>i32</code>、<code>i64</code>、<code>i128</code> 和 <code>isize</code>（指针宽度）</li>
<li>无符号整数（unsigned integers）： <code>u8</code>、<code>u16</code>、<code>u32</code>、<code>u64</code>、<code>u128</code> 和 <code>usize</code>（指针宽度）</li>
<li>浮点数（floating point）： <code>f32</code>、<code>f64</code></li>
<li><code>char</code>（字符）：单个 Unicode 字符，如 <code>&#39;a&#39;</code>，<code>&#39;α&#39;</code> 和 <code>&#39;∞&#39;</code>（每个都是 4 字节）</li>
<li><code>bool</code>（布尔型）：只能是 <code>true</code> 或 <code>false</code></li>
<li>单元类型（unit type）：<code>()</code>。其唯一可能的值就是 <code>()</code> 这个空元组</li>
</ul>
<p>尽管单元类型的值是个元组，它却并不被认为是复合类型，因为并不包含多个值。</p>
<h3 id="复合类型（compound-type）"><a href="#复合类型（compound-type）" class="headerlink" title="复合类型（compound type）"></a>复合类型（compound type）</h3><ul>
<li>数组（array）：如 <code>[1, 2, 3]</code></li>
<li>元组（tuple）：如 <code>(1, true)</code></li>
</ul>
<p>变量都能够显式地给出<strong>类型说明</strong>（type annotation）。数字还可以通过<strong>后缀</strong>（suffix）或<strong>默认方式</strong>来声明类型。整型默认为 <code>i32</code> 类型，浮点型默认为 <code>f64</code>类型。注意 Rust 还可以根据上下文来推断（infer）类型（译注：比如一个未声明类型整数和 <code>i64</code> 的整数相加，则该整数会自动推断为 <code>i64</code> 类型。仅当根据环境无法推断时，才按默认方式取整型数值为 <code>i32</code>，浮点数值为 <code>f64</code>）。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">fn main() &#123;</span><br><span class="line">    // 变量可以给出类型说明。</span><br><span class="line">    let logical: bool = true;</span><br><span class="line">    let a_float: f64 = 1.0;  // 常规说明</span><br><span class="line">    let an_integer   = 5i32; // 后缀说明</span><br><span class="line">    // 否则会按默认方式决定类型。</span><br><span class="line">    let default_float   = 3.0; // `f64`</span><br><span class="line">    let default_integer = 7;   // `i32`</span><br><span class="line">    // 类型也可根据上下文自动推断。</span><br><span class="line">    let mut inferred_type = 12; // 根据下一行的赋值推断为 i64 类型</span><br><span class="line">    inferred_type = 4294967296i64;</span><br><span class="line">    // 可变的（mutable）变量，其值可以改变。</span><br><span class="line">    let mut mutable = 12; // Mutable `i32`</span><br><span class="line">    mutable = 21;</span><br><span class="line">    // 报错！变量的类型并不能改变。</span><br><span class="line">    mutable = true;</span><br><span class="line">    // 但可以用遮蔽（shadow）来覆盖前面的变量。</span><br><span class="line">    let mutable = true;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="字面量和运算符"><a href="#字面量和运算符" class="headerlink" title="字面量和运算符"></a>字面量和运算符</h3><p>整数 <code>1</code>、浮点数 <code>1.2</code>、字符 <code>&#39;a&#39;</code>、字符串 <code>&quot;abc&quot;</code>、布尔值 <code>true</code> 和单元类型 <code>()</code> 可以用数字、文字或符号之类的 “字面量”（literal）来表示。</p>
<p>另外，通过加前缀 <code>0x</code>、<code>0o</code>、<code>0b</code>，数字可以用十六进制、八进制或二进制记法表示。</p>
<p>为了改善可读性，可以在数值字面量中插入下划线，比如：<code>1_000</code> 等同于 <code>1000</code>，<code>0.000_001</code> 等同于 <code>0.000001</code>。</p>
<p>我们需要把字面量的类型告诉编译器。如前面学过的，我们使用 <code>u32</code> 后缀来表明字面量是一个 32 位无符号整数，<code>i32</code> 后缀表明字面量是一个 32 位有符号整数。</p>
<p>[Rust][rust op-prec] 提供了一系列的运算符（operator），它们的优先级和[类 C 语言][op-prec]类似。（译注：类 C 语言包括 C&#x2F;C++、Java、PHP 等语言）</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">fn main() &#123;</span><br><span class="line">    // 整数相加</span><br><span class="line">    println!(&quot;1 + 2 = &#123;&#125;&quot;, 1u32 + 2);</span><br><span class="line">    // 整数相减</span><br><span class="line">    println!(&quot;1 - 2 = &#123;&#125;&quot;, 1i32 - 2);</span><br><span class="line">    // 试一试 ^ 尝试将 `1i32` 改为 `1u32`，体会为什么类型声明这么重要</span><br><span class="line">    // 短路求值的布尔逻辑</span><br><span class="line">    println!(&quot;true AND false is &#123;&#125;&quot;, true &amp;&amp; false);</span><br><span class="line">    println!(&quot;true OR false is &#123;&#125;&quot;, true || false);</span><br><span class="line">    println!(&quot;NOT true is &#123;&#125;&quot;, !true);</span><br><span class="line">    // 位运算</span><br><span class="line">    println!(&quot;0011 AND 0101 is &#123;:04b&#125;&quot;, 0b0011u32 &amp; 0b0101);</span><br><span class="line">    println!(&quot;0011 OR 0101 is &#123;:04b&#125;&quot;, 0b0011u32 | 0b0101);</span><br><span class="line">    println!(&quot;0011 XOR 0101 is &#123;:04b&#125;&quot;, 0b0011u32 ^ 0b0101);</span><br><span class="line">    println!(&quot;1 &lt;&lt; 5 is &#123;&#125;&quot;, 1u32 &lt;&lt; 5);</span><br><span class="line">    println!(&quot;0x80 &gt;&gt; 2 is 0x&#123;:x&#125;&quot;, 0x80u32 &gt;&gt; 2);</span><br><span class="line">    // 使用下划线改善数字的可读性！</span><br><span class="line">    println!(&quot;One million is written as &#123;&#125;&quot;, 1_000_000u32);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="元组"><a href="#元组" class="headerlink" title="元组"></a>元组</h3><p>元组是一个可以包含各种类型值的组合。元组使用括号 <code>()</code> 来构造（construct），而每个元组自身又是一个类型标记为 <code>(T1, T2, ...)</code> 的值，其中 <code>T1</code>、<code>T2</code> 是每个元素的类型。函数可以使用元组来返回多个值，因为元组可以拥有任意多个值。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">// 元组可以充当函数的参数和返回值</span><br><span class="line">fn reverse(pair: (i32, bool)) -&gt; (bool, i32) &#123;</span><br><span class="line">    // 可以使用 `let` 把一个元组的成员绑定到一些变量</span><br><span class="line">    let (integer, boolean) = pair;</span><br><span class="line">    (boolean, integer)</span><br><span class="line">&#125;</span><br><span class="line">// 在 “动手试一试” 的练习中要用到下面这个结构体。</span><br><span class="line">#[derive(Debug)]</span><br><span class="line">struct Matrix(f32, f32, f32, f32);</span><br><span class="line">fn main() &#123;</span><br><span class="line">    // 包含各种不同类型的元组</span><br><span class="line">    let long_tuple = (1u8, 2u16, 3u32, 4u64,</span><br><span class="line">                      -1i8, -2i16, -3i32, -4i64,</span><br><span class="line">                      0.1f32, 0.2f64,</span><br><span class="line">                      &#x27;a&#x27;, true);</span><br><span class="line">    // 通过元组的下标来访问具体的值</span><br><span class="line">    println!(&quot;long tuple first value: &#123;&#125;&quot;, long_tuple.0);</span><br><span class="line">    println!(&quot;long tuple second value: &#123;&#125;&quot;, long_tuple.1);</span><br><span class="line">    // 元组也可以充当元组的元素</span><br><span class="line">    let tuple_of_tuples = ((1u8, 2u16, 2u32), (4u64, -1i8), -2i16);</span><br><span class="line">    // 元组可以打印</span><br><span class="line">    println!(&quot;tuple of tuples: &#123;:?&#125;&quot;, tuple_of_tuples);</span><br><span class="line">    // 但很长的元组无法打印</span><br><span class="line">    // let too_long_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);</span><br><span class="line">    // println!(&quot;too long tuple: &#123;:?&#125;&quot;, too_long_tuple);</span><br><span class="line">    // 试一试 ^ 取消上面两行的注释，阅读编译器给出的错误信息。</span><br><span class="line">    let pair = (1, true);</span><br><span class="line">    println!(&quot;pair is &#123;:?&#125;&quot;, pair);</span><br><span class="line">    println!(&quot;the reversed pair is &#123;:?&#125;&quot;, reverse(pair));</span><br><span class="line">    // 创建单元素元组需要一个额外的逗号，这是为了和被括号包含的字面量作区分。</span><br><span class="line">    println!(&quot;one element tuple: &#123;:?&#125;&quot;, (5u32,));</span><br><span class="line">    println!(&quot;just an integer: &#123;:?&#125;&quot;, (5u32));</span><br><span class="line">    // 元组可以被解构（deconstruct），从而将值绑定给变量</span><br><span class="line">    let tuple = (1, &quot;hello&quot;, 4.5, true);</span><br><span class="line">    let (a, b, c, d) = tuple;</span><br><span class="line">    println!(&quot;&#123;:?&#125;, &#123;:?&#125;, &#123;:?&#125;, &#123;:?&#125;&quot;, a, b, c, d);</span><br><span class="line">    let matrix = Matrix(1.1, 1.2, 2.1, 2.2);</span><br><span class="line">    println!(&quot;&#123;:?&#125;&quot;, matrix)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="数组和切片"><a href="#数组和切片" class="headerlink" title="数组和切片"></a>数组和切片</h3><p>数组（array）是一组拥有相同类型 <code>T</code> 的对象的集合，在内存中是连续存储的。数组使用中括号 <code>[]</code> 来创建，且它们的大小在编译时会被确定。数组的类型标记为 <code>[T; length]</code>（译注：<code>T</code> 为元素类型，<code>length</code> 表示数组大小）。</p>
<p>切片（slice）类型和数组类似，但其大小在编译时是不确定的。相反，切片是一个双字对象（two-word object），第一个字是一个指向数据的指针，第二个字是切片的长度。这个 “字” 的宽度和 usize 相同，由处理器架构决定，比如在 x86-64 平台上就是 64 位。slice 可以用来借用数组的一部分。slice 的类型标记为 <code>&amp;[T]</code>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">use std::mem;</span><br><span class="line">// 此函数借用一个 slice</span><br><span class="line">fn analyze_slice(slice: &amp;[i32]) &#123;</span><br><span class="line">    println!(&quot;first element of the slice: &#123;&#125;&quot;, slice[0]);</span><br><span class="line">    println!(&quot;the slice has &#123;&#125; elements&quot;, slice.len());</span><br><span class="line">&#125;</span><br><span class="line">fn main() &#123;</span><br><span class="line">    // 定长数组（类型标记是多余的）</span><br><span class="line">    let xs: [i32; 5] = [1, 2, 3, 4, 5];</span><br><span class="line">    // 所有元素可以初始化成相同的值</span><br><span class="line">    let ys: [i32; 500] = [0; 500];</span><br><span class="line">    // 下标从 0 开始</span><br><span class="line">    println!(&quot;first element of the array: &#123;&#125;&quot;, xs[0]);</span><br><span class="line">    println!(&quot;second element of the array: &#123;&#125;&quot;, xs[1]);</span><br><span class="line">    // `len` 返回数组的大小</span><br><span class="line">    println!(&quot;array size: &#123;&#125;&quot;, xs.len());</span><br><span class="line">    // 数组是在栈中分配的</span><br><span class="line">    println!(&quot;array occupies &#123;&#125; bytes&quot;, mem::size_of_val(&amp;xs));</span><br><span class="line">    // 数组可以自动被借用成为 slice</span><br><span class="line">    println!(&quot;borrow the whole array as a slice&quot;);</span><br><span class="line">    analyze_slice(&amp;xs);</span><br><span class="line">    // slice 可以指向数组的一部分</span><br><span class="line">    println!(&quot;borrow a section of the array as a slice&quot;);</span><br><span class="line">    analyze_slice(&amp;ys[1 .. 4]);</span><br><span class="line">    // 越界的下标会引发致命错误（panic）</span><br><span class="line">    println!(&quot;&#123;&#125;&quot;, xs[5]);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="自定义类型"><a href="#自定义类型" class="headerlink" title="自定义类型"></a>自定义类型</h2><p>Rust 自定义数据类型主要是通过下面这两个关键字来创建：</p>
<ul>
<li><code>struct</code>： 定义一个结构体（structure）</li>
<li><code>enum</code>： 定义一个枚举类型（enumeration）</li>
</ul>
<p>而常量（constant）可以通过 <code>const</code> 和 <code>static</code> 关键字来创建。</p>
<h3 id="结构体"><a href="#结构体" class="headerlink" title="结构体"></a>结构体</h3><p>结构体（structure，缩写成 struct）有 3 种类型，使用 <code>struct</code> 关键字来创建：</p>
<ul>
<li>元组结构体（tuple struct），事实上就是具名元组而已。</li>
<li>经典的 [C 语言风格结构体][c_struct]（C struct）。</li>
<li>单元结构体（unit struct），不带字段，在泛型中很有用。</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">#[derive(Debug)]</span><br><span class="line">struct Person &#123;</span><br><span class="line">    name: String,</span><br><span class="line">    age: u8,</span><br><span class="line">&#125;</span><br><span class="line">// 单元结构体</span><br><span class="line">struct Unit;</span><br><span class="line">// 元组结构体</span><br><span class="line">struct Pair(i32, f32);</span><br><span class="line">// 带有两个字段的结构体</span><br><span class="line">struct Point &#123;</span><br><span class="line">    x: f32,</span><br><span class="line">    y: f32,</span><br><span class="line">&#125;</span><br><span class="line">// 结构体可以作为另一个结构体的字段</span><br><span class="line">#[allow(dead_code)]</span><br><span class="line">struct Rectangle &#123;</span><br><span class="line">    // 可以在空间中给定左上角和右下角在空间中的位置来指定矩形。</span><br><span class="line">    top_left: Point,</span><br><span class="line">    bottom_right: Point,</span><br><span class="line">&#125;</span><br><span class="line">fn main() &#123;</span><br><span class="line">    // 使用简单的写法初始化字段，并创建结构体</span><br><span class="line">    let name = String::from(&quot;Peter&quot;);</span><br><span class="line">    let age = 27;</span><br><span class="line">    let peter = Person &#123; name, age &#125;;</span><br><span class="line">    // 以 Debug 方式打印结构体</span><br><span class="line">    println!(&quot;&#123;:?&#125;&quot;, peter);</span><br><span class="line">    // 实例化结构体 `Point`</span><br><span class="line">    let point: Point = Point &#123; x: 10.3, y: 0.4 &#125;;</span><br><span class="line">    // 访问 point 的字段</span><br><span class="line">    println!(&quot;point coordinates: (&#123;&#125;, &#123;&#125;)&quot;, point.x, point.y);</span><br><span class="line">    // 使用结构体更新语法创建新的 point，</span><br><span class="line">    // 这样可以用到之前的 point 的字段</span><br><span class="line">    let bottom_right = Point &#123; x: 5.2, ..point &#125;;</span><br><span class="line">    // `bottom_right.y` 与 `point.y` 一样，因为这个字段就是从 `point` 中来的</span><br><span class="line">    println!(&quot;second point: (&#123;&#125;, &#123;&#125;)&quot;, bottom_right.x, bottom_right.y);</span><br><span class="line">    // 使用 `let` 绑定来解构 point</span><br><span class="line">    let Point &#123; x: left_edge, y: top_edge &#125; = point;</span><br><span class="line">    let _rectangle = Rectangle &#123;</span><br><span class="line">        // 结构体的实例化也是一个表达式</span><br><span class="line">        top_left: Point &#123; x: left_edge, y: top_edge &#125;,</span><br><span class="line">        bottom_right: bottom_right,</span><br><span class="line">    &#125;;</span><br><span class="line">    // 实例化一个单元结构体</span><br><span class="line">    let _unit = Unit;</span><br><span class="line">    // 实例化一个元组结构体</span><br><span class="line">    let pair = Pair(1, 0.1);</span><br><span class="line">    // 访问元组结构体的字段</span><br><span class="line">    println!(&quot;pair contains &#123;:?&#125; and &#123;:?&#125;&quot;, pair.0, pair.1);</span><br><span class="line">    // 解构一个元组结构体</span><br><span class="line">    let Pair(integer, decimal) = pair;</span><br><span class="line">    println!(&quot;pair contains &#123;:?&#125; and &#123;:?&#125;&quot;, integer, decimal);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="枚举"><a href="#枚举" class="headerlink" title="枚举"></a>枚举</h3><p><code>enum</code> 关键字允许创建一个从数个不同取值中选其一的枚举类型（enumeration）。任何一个在 <code>struct</code> 中合法的取值在 <code>enum</code> 中也合法。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">// 该属性用于隐藏对未使用代码的警告。</span><br><span class="line">#![allow(dead_code)]</span><br><span class="line">// 创建一个 `enum`（枚举）来对 web 事件分类。注意变量名和类型共同指定了 `enum`</span><br><span class="line">// 取值的种类：`PageLoad` 不等于 `PageUnload`，`KeyPress(char)` 不等于</span><br><span class="line">// `Paste(String)`。各个取值不同，互相独立。</span><br><span class="line">enum WebEvent &#123;</span><br><span class="line">    // 一个 `enum` 可以是单元结构体（称为 `unit-like` 或 `unit`），</span><br><span class="line">    PageLoad,</span><br><span class="line">    PageUnload,</span><br><span class="line">    // 或者一个元组结构体，</span><br><span class="line">    KeyPress(char),</span><br><span class="line">    Paste(String),</span><br><span class="line">    // 或者一个普通的结构体。</span><br><span class="line">    Click &#123; x: i64, y: i64 &#125;</span><br><span class="line">&#125;</span><br><span class="line">// 此函数将一个 `WebEvent` enum 作为参数，无返回值。</span><br><span class="line">fn inspect(event: WebEvent) &#123;</span><br><span class="line">    match event &#123;</span><br><span class="line">        WebEvent::PageLoad =&gt; println!(&quot;page loaded&quot;),</span><br><span class="line">        WebEvent::PageUnload =&gt; println!(&quot;page unloaded&quot;),</span><br><span class="line">        // 从 `enum` 里解构出 `c`。</span><br><span class="line">        WebEvent::KeyPress(c) =&gt; println!(&quot;pressed &#x27;&#123;&#125;&#x27;.&quot;, c),</span><br><span class="line">        WebEvent::Paste(s) =&gt; println!(&quot;pasted \&quot;&#123;&#125;\&quot;.&quot;, s),</span><br><span class="line">        // 把 `Click` 解构给 `x` and `y`。</span><br><span class="line">        WebEvent::Click &#123; x, y &#125; =&gt; &#123;</span><br><span class="line">            println!(&quot;clicked at x=&#123;&#125;, y=&#123;&#125;.&quot;, x, y);</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">fn main() &#123;</span><br><span class="line">    let pressed = WebEvent::KeyPress(&#x27;x&#x27;);</span><br><span class="line">    // `to_owned()` 从一个字符串切片中创建一个具有所有权的 `String`。</span><br><span class="line">    let pasted  = WebEvent::Paste(&quot;my text&quot;.to_owned());</span><br><span class="line">    let click   = WebEvent::Click &#123; x: 20, y: 80 &#125;;</span><br><span class="line">    let load    = WebEvent::PageLoad;</span><br><span class="line">    let unload  = WebEvent::PageUnload;</span><br><span class="line">    inspect(pressed);</span><br><span class="line">    inspect(pasted);</span><br><span class="line">    inspect(click);</span><br><span class="line">    inspect(load);</span><br><span class="line">    inspect(unload);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="类型别名"><a href="#类型别名" class="headerlink" title="类型别名"></a>类型别名</h4><p>若使用类型别名，则可以通过其别名引用每个枚举变量。当枚举的名称太长或者太一般化，且你想要对其重命名，那么这对你会有所帮助。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">enum VeryVerboseEnumOfThingsToDoWithNumbers &#123;</span><br><span class="line">    Add,</span><br><span class="line">    Subtract,</span><br><span class="line">&#125;</span><br><span class="line">// 创建一个类型别名</span><br><span class="line">type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;</span><br><span class="line">fn main() &#123;</span><br><span class="line">    // 我们可以通过别名引用每个枚举变量，避免使用又长又不方便的枚举名字</span><br><span class="line">    let x = Operations::Add;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>最常见的情况就是在 <code>impl</code> 块中使用 <code>Self</code> 别名。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">enum VeryVerboseEnumOfThingsToDoWithNumbers &#123;</span><br><span class="line">    Add,</span><br><span class="line">    Subtract,</span><br><span class="line">&#125;</span><br><span class="line">impl VeryVerboseEnumOfThingsToDoWithNumbers &#123;</span><br><span class="line">    fn run(&amp;self, x: i32, y: i32) -&gt; i32 &#123;</span><br><span class="line">        match self &#123;</span><br><span class="line">            Self::Add =&gt; x + y,</span><br><span class="line">            Self::Subtract =&gt; x - y,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>该功能已在 Rust 中稳定下来， 可以阅读 [stabilization report][aliasreport] 来了解更多有关枚举和类型别名的知识。</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/Rust/rust-by-example-1/" title="通过例子学 Rust">https://wyatex.online/Rust/rust-by-example-1/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
              <a href="/tags/Rust/" rel="tag"># Rust</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/ChatGpt/chatgpt-guide/" rel="prev" title="chatGPT（VX版）使用说明书">
                  <i class="fa fa-angle-left"></i> chatGPT（VX版）使用说明书
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/%E5%BF%AB%E9%80%9F%E6%90%AD%E5%BB%BAk8s%E5%B9%B3%E5%8F%B0/" rel="next" title="快速搭建k8s平台">
                  快速搭建k8s平台 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
